package org.tsinghua.answer.domain.user;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tsinghua.answer.domain.subject.Subject;
import org.tsinghua.answer.domain.subject.SubjectRepository;
import org.tsinghua.answer.domain.user.exception.EmailException;
import org.tsinghua.answer.domain.user.exception.PasswordException;
import org.tsinghua.answer.domain.user.exception.UsernameException;
import org.tsinghua.answer.utils.AuthUtils;
import org.tsinghua.answer.utils.PageableBuilder;

@Transactional
@Service
public class UserService {
	
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private UserSubjectRepository userSubjectRepository;
	@Autowired
	private SubjectRepository subjectRepository;

	@Autowired
	private PasswordEncoder passwordEncoder;
	
	public Page<User> volunteers(String keyword, int page, int size) {
		if(StringUtils.isBlank(keyword)) {
			keyword = "%";
		} else {
			keyword = "%" + keyword + "%";
		}
		Pageable pageable = PageableBuilder.build(page, size);
		return userRepository.volunteers(keyword, pageable);
	}
	
	public User registUser(User user) throws UsernameException, EmailException, PasswordException {
		if(user.getType() == UserType.VOLUNTEER) {
			return registVolunteer(user);
		}
		registCheck(user);
		String username = user.getUsername();
		String email = user.getEmail();
		String password = passwordEncoder.encode(user.getPassword());
		String nickname = user.getNickname();
		Sex sex = user.getSex();
		String profile = user.getProfile();
		user = User.user(username, password, nickname, email, sex, profile);
		//暂时不需要验证邮箱
		user.setVerified(true);
		userRepository.save(user);
		return user;
	}
	
	public User registVolunteer(User user) throws UsernameException, EmailException, PasswordException {
		registCheck(user);
		String username = user.getUsername();
		String email = user.getEmail();
		String password = passwordEncoder.encode(user.getPassword());
		String nickname = user.getNickname();
		Sex sex = user.getSex();
		String profile = user.getProfile();
		List<String> subjectIds = user.getSubjectIds();
		user = User.volunteer(username, password, nickname, email, sex, profile);
		//暂时直接通过审核
		user.setVerified(true);
		user.setAuthenticated(true);
		userRepository.save(user);
		String id = user.getId();
		if( CollectionUtils.isNotEmpty(subjectIds) ) {
			saveUserSubjects(id, subjectIds);
		}
		user = userRepository.findOne(id);
		return user;
	}
	
	public User updateUserProfile(User user) throws PasswordException, EmailException {
		User self = AuthUtils.getUser();
		self = userRepository.findOne(self.getId());
		if(user == null) return self;
		if(StringUtils.isNotBlank(user.getPassword())) {
			if(StringUtils.isBlank(user.getOldPassword())) {
				throw new PasswordException("请填写原密码");
			}
			String oldPassword = user.getOldPassword();
			if(passwordEncoder.matches(oldPassword, self.getPassword())) {
				String password = user.getPassword();
				checkPassword(password);
				self.setPassword(passwordEncoder.encode(password));
			} else {
				throw new PasswordException("原始密码错误");
			}
		}
		if(StringUtils.isNotBlank(user.getNickname())) {
			self.setNickname(user.getNickname());
		}
		String email = user.getEmail();
		if(StringUtils.isNotBlank(email) && !self.getEmail().equals(email)) {
			checkEmail(email);
			self.setEmail(email);
		}
		if(user.getProfile() != null) {
			self.setProfile(user.getProfile());
		}
		self = userRepository.save(self);
		
		//单独为volunteer提供的更新字段
		if(self.getType() == UserType.VOLUNTEER && CollectionUtils.isNotEmpty(user.getSubjectIds())) {
			saveUserSubjects(self.getId(), user.getSubjectIds());
		}
		return self;
	}
	
	public static boolean isValidEmailAddress(String email) {
	   boolean result = true;
	   try {
	      InternetAddress emailAddr = new InternetAddress(email);
	      emailAddr.validate();
	   } catch (AddressException ex) {
	      result = false;
	   }
	   return result;
	}
	
	public void registCheck(User user) throws UsernameException, EmailException, PasswordException {
		String username = user.getUsername();
		checkUsername(username);
		String email = user.getEmail();
		checkEmail(email);
		String password = user.getPassword();
		checkPassword(password);
	}
	
	public void checkUsername(String username) throws UsernameException {
		if(StringUtils.isBlank(username)) {
			throw new UsernameException("请填写用户名");
		}
		if(userRepository.findByUsername(username) != null) {
			throw new UsernameException("用户名已经存在");
		}
	}
	
	public void checkPassword(String password) throws PasswordException {
		if(StringUtils.isBlank(password)) {
			throw new PasswordException("请填写密码");
		}
		if(password.length() < 6) {
			throw new PasswordException("请填写至少六位密码");
		}
	}
	
	public void checkEmail(String email) throws EmailException {
		if(StringUtils.isBlank(email)) {
			throw new EmailException("请填写邮箱地址");
		}
		if(userRepository.findByEmail(email) != null) {
			throw new EmailException("邮箱已经被使用");
		}
		if(!isValidEmailAddress(email)) {
			throw new EmailException("请填写真实的邮箱地址");
		}
	}
	
	public void saveUserSubjects(String userId, Collection<String> subjectIds) {
		userSubjectRepository.deleteByUserId(userId);
		if(CollectionUtils.isEmpty(subjectIds)) {
			return;
		}
		User user = userRepository.findOne(userId);
		List<Subject> subjects = subjectRepository.findAll(subjectIds);
		List<UserSubject> userSubjects = new ArrayList<>();
		for (Subject subject : subjects) {
			UserSubject userSubject = new UserSubject(user, subject);
			userSubjects.add(userSubject);
		}
		userSubjectRepository.save(userSubjects);
	}
}
